﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class Active : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //显示验证码  
        string code = GenCode(4);
        this.GenImg(code);
        Session["image"] = code;
    }


    private string GenCode(int num)
    {
        //string[] source = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P,", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        string[] source = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        string code = "";
        //创建Random类的实例  
        Random rd = new Random();
        //获取验证码  
        for (int i = 0; i < num; i++)
        {
            code += source[rd.Next(0, source.Length)];

        }
        //返回产生的验证码  
        return code;
    }

    //生成图片  
    private void GenImg(string code)
    {
        //定义一个画板  
        Bitmap myPalette = new Bitmap(80, 35);
        //在画板上定义绘图的实例  
        Graphics gh = Graphics.FromImage(myPalette);
        //定义一个矩形  
        Rectangle rc = new Rectangle(0, 0, 80, 35);
        //填充矩形  
        gh.FillRectangle(new SolidBrush(Color.Silver), rc);
        //在矩形内画出字符串  
        gh.DrawString(code, new Font("宋体", 20), new SolidBrush(Color.White), rc);
        //将图片显示出来  
        myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        gh.Dispose();
        myPalette.Dispose();
    }
}